<template>
	<view class="page">
		<view class="title">{{ form.examName }}</view>
		<view class="form">
			<swiper class="swiper" :current="currentIndex" @change="swiperChange">
				<swiper-item v-for="(question, index) in questions" :key="index">
					<view class="question">
						<view class="question-title">{{ question.questionName }}</view>
						<view v-if="question.type == '填空'">
							<u--textarea v-model="question.answerValue" placeholder="请输入答案" :height="1000"
								count></u--textarea>
						</view>
						<view v-else-if="question.type == '单选'">
							<u-radio-group size="35" iconSize="35" v-model="question.answerValue" placement="column"
								@change="groupChange">
								<u-radio labelSize="35" :customStyle="{ marginBottom: '55rpx' }"
									v-for="(childrenItem, index) in question.children" :key="index"
									:label="childrenItem.questionName" :name="childrenItem.questionName"
									@change="radioChange">
								</u-radio>
							</u-radio-group>
						</view>
						<view v-else-if="question.type == '多选'">
							<u-checkbox-group v-model="question.answerValue" placement="column"
								@change="checkboxChange">
								<u-checkbox size="35" labelSize="35" iconSize="35"
									:customStyle="{ marginBottom: '55rpx' }"
									v-for="(childrenItem, index) in question.children" :key="index"
									:label="childrenItem.questionName" :name="childrenItem.questionName">
								</u-checkbox>
							</u-checkbox-group>
						</view>
					</view>
				</swiper-item>
			</swiper>
		</view>
		<view class="controls">
			<view class="prev-button" @click="prevQuestion">上一题</view>
			<view class="next-button" @click="nextQuestion">下一题</view>
		</view>
		<view v-show="currentIndex == questions.length - 1" class="submit-button">
			<button type="primary" @click="submitForm">提交</button>
		</view>
	</view>
</template>

<script>
	import {
		listAssignDetail,
		getAssignDetail,
		delAssignDetail,
		addAssignDetail,
		updateAssignDetail,
	} from "@/api/elder/questionnaire/assignDetail";

	import {
		listAnswer,
		getAnswer,
		delAnswer,
		addAnswer,
		updateAnswer,
	} from "@/api/elder/questionnaire/answer";

	import {
		listQuestion
	} from "@/api/elder/questionnaire/question";

	import {
		transformPostBody,
		transformRequestURL,
	} from "@/api/queryParam/index.js";

	//考卷做题页
	export default {
		data() {
			return {
				form: {
					examName: "问卷名称",
					respondent: "",
					answers: [],
				},
				queryParams: {
					pageNum: 1,
					pageSize: 1000,
					paperId: null,
				},
				answerList: [],
				currentIndex: 0,
				questions: [],
				errors: [],
				assignId: "",
				assignDetailId: "",
				paperId: "",
			};
		},
		onLoad: function(options) {
			console.log("options", options);
			this.assignId = options.assignId;
			this.assignDetailId = options.assignDetailId;
			this.paperId = options.paperId;
		},
		onShow() {
			this.getList();
		},
		methods: {
			async getList() {
				this.loading = true;
				this.queryParams.paperId = this.paperId; //获取试卷题目
				this.queryParams.assignDetailId = this.assignDetailId; //获取之前做题答案
				await listAnswer(transformRequestURL(this.queryParams)).then(
					(response_ans) => {
						console.log("listAnswer", response_ans);
						this.answerList = response_ans.rows;
					}
				);
				await listQuestion(transformRequestURL(this.queryParams)).then(
					(response_ques) => {
						// console.log("listQuestion", response_ques);
						let rootNodes = [];
						response_ques.data.forEach((item) => {
							if (item.parentQuestionid == 0) {
								rootNodes.push(item);
								//通过this.answerList中的数据，将答案赋值给题目的answerValue
								item.answerValue = null;
								this.answerList.forEach((item2) => {
									if (item.questionId == item2.questionId) {
										item.answerValue = item2.answerValue;
									}
								});
							}
						});
						rootNodes.forEach((item) => {
							item.children = [];
							response_ques.data.forEach((item2) => {
								if (item2.parentQuestionid == item.questionId) {
									item.children.push(item2);
								}
							});
						});
						// console.log("rootNodes", rootNodes);
						this.questions = this.formartQuestions(rootNodes);
						this.loading = false;
						console.log("questions", this.questions);
					}
				);
			},
			//将树形结构转化为要求的结构
			formartQuestions(rootNodes) {
				let result = [];
				//树状遍历rootNodes，按一下规则进行转化
				//所有节点添加属性type，满足转化关系，函数：formartquestionType(questionType)
				//在根节点添加属性answerValue，用于存放答案

				//遍历节点，只有两层
				rootNodes.forEach((item) => {
					let question = {};
					question.questionId = item.questionId;
					question.questionName = item.questionName;
					question.questionType = item.questionType;
					question.type = this.formartquestionType(item.questionType);
					question.answerValue = item.answerValue;
					question.children = [];
					item.children.forEach((item2) => {
						let question2 = {};
						question2.questionId = item2.questionId;
						question2.questionName = item2.questionName;
						question2.questionType = item2.questionType;
						question2.type = this.formartquestionType(item2.questionType);
						// question2.answerValue =  item.answerValue
						question2.children = [];
						question.children.push(question2);
					});
					result.push(question);
				});
				return result;
			},
			//转化questionType
			formartquestionType(questionType) {
				switch (questionType) {
					case "1":
						return "填空";
					case "2":
						return "单选";
					case "3":
						return "多选";
					case "0":
						return "主标题";
					case "21":
						return "只需选择";
					case "22":
						return "选择带填空";
					default:
						return "";
				}
			},

			prevQuestion() {
				if (this.currentIndex > 0) {
					this.currentIndex--;
				}
			},
			nextQuestion() {
				if (this.currentIndex < this.questions.length - 1) {
					this.currentIndex++;
				}
			},
			swiperChange({
				detail: {
					current
				}
			}) {
				this.currentIndex = current;
			},
			submitForm() {
				this.errors = [];
				// 表单校验
				// for (let i = 0; i < this.questions.length; i++) {
				// 	const field = `answers.${i}`;
				// 	this.$refs.form.validateField(field, (error) => {
				// 		this.errors[i] = error ? error[0].message : "";
				// 	});
				// }

				// 判断是否所有题目都回答完整
				const isComplete = this.errors.every((error) => !error);
				if (isComplete) {
					console.log(this.form);
					//遍历this.questions跟节点的answerValue调用updateAnswer更新答案
					this.questions.forEach((item) => {
						let answer = {};
						answer.assignId = this.assignId;
						answer.assignDetailId = this.assignDetailId;
						answer.questionId = item.questionId;
						answer.answerValue = item.answerValue;
						console.log("answer", answer);
						updateAnswer(answer).then((response) => {
							console.log("updateAnswer", response);
						});
					});
				} else {
					uni.showToast({
						title: "请填写完整问卷",
						icon: "none",
					});
				}
			},
			checkboxChange(n) {
				console.log("change", n);
			},
			groupChange(n) {
				console.log("groupChange", n);
			},
			radioChange(n) {
				console.log("radioChange", n);
			},
		},
	};
</script>

<style scoped>
	.page {
		padding: 20rpx;
		height: 100%;
	}

	.title {
		text-align: center;
		font-size: 50rpx;
		margin-bottom: 20rpx;
		font-weight: 600;
	}

	.form {
		height: 1200rpx;
		overflow: hidden;
	}

	.swiper {
		height: 100%;
	}

	.swiper-item {
		display: flex;
		align-items: center;
		justify-content: center;
	}

	.question {
		height: 80%;
		/* margin-bottom: 20rpx; */
		/* text-align: center; */
	}

	.question-title {
		font-size: 60rpx;
		text-align: left;
		margin-bottom: 40rpx;
		font-weight: 600;
	}

	.controls {
		display: flex;
		justify-content: space-between;
		margin-top: 20rpx;
		/* bottom: 20rpx; */
	}

	.prev-button,
	.next-button {
		width: 220rpx;
		height: 60rpx;
		/* line-height: 40rpx; */
		text-align: center;
		background-color: #ccc;
		border-radius: 4rpx;
		color: #fff;
		cursor: pointer;
		font-size: 35rpx;
	}

	.submit-button {
		display: flex;
		justify-content: center;
		margin-top: 20rpx;
	}
</style>